package dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import dao.CustomerDao;
import dao.RowMapper;
import entity.Customer;
//HanMan
public class CustomerDaoImpl implements CustomerDao {
	JDBCTemplate jdbc = new JDBCTemplate();
	private class rowMapperImpl implements RowMapper<Customer>{
		@Override
		public Customer rowMapper(ResultSet rs) throws SQLException {
			//cusId, userName, password, phone, registerDate, email, addressList
			return new Customer(rs.getInt("cusId"),rs.getString("userName"),rs.getString("password"),rs.getString("phone"),
					rs.getDate("registerDate"),rs.getString("email"),null);
		}	
	}
	@Override
	public Customer queryCustomer(String userName, String password) {
		return jdbc.queryOne("select * from Customer where username=? and password=?",new rowMapperImpl(),userName,password);
	}

	@Override
	public void addCustomer(Customer customer) {
		jdbc.CUDObject("insert into Customer(username,password,phone,registerDate,Email)values(?,?,?,?,?)",customer.getUserName(),customer.getPassword(),customer.getPhone(),customer.getRegisterDate(),customer.getEmail());
	}

	@Override
	public void updateCustomer(Customer customer) {
		jdbc.CUDObject("update Customer set username=? ,password=? ,phone=?,registerDate=?,Email=? where cusId=?",customer.getUserName(),customer.getPassword(),customer.getPhone(),customer.getRegisterDate(),customer.getEmail(),customer.getCusId());
	}

	@Override
	public Customer queryCustomer(int customerId) {
		return jdbc.queryOne("select * from Customer where cusId=?", new rowMapperImpl(), customerId);
	}
	
	public static void main(String[] args) {
		CustomerDaoImpl impl = new CustomerDaoImpl();
		System.out.println(impl.queryCustomer(1).getUserName());
	}

	@Override
	public boolean queryCustomerExists(String userName) {
		String sql="SELECT COUNT(*) FROM Customer WHERE username=?";
		Integer num=jdbc.queryOne(sql,new RowMapper<Integer>(){
			@Override
			public Integer rowMapper(ResultSet rs) throws SQLException {
				return rs.getInt(1);
			}
		}, userName);
		return num>0;
	}

	@Override
	public List<Customer> queryAllCustomer() {
		String sql="select * from Customer";
		return jdbc.queryAll(sql, new rowMapperImpl());
	}
}
